package com.example.demo.eight;

import com.example.demo.util.RabbitMQUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;

import java.util.HashMap;
import java.util.Map;

/**
 * 死信队列
 *
 * @author chensixiang chensixiang1234@gmail.com
 */
public class Consumer01 {
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    public static final String DEAD_EXCHANGE = "dead_exchange";
    public static final String NORMAL_QUEUE = "normal_queue";
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMQUtils.getChannel();
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        Map<String, Object> arguments = new HashMap<>();
        // 设置死信交换机
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        // 设置死信RoutingKey
        arguments.put("x-dead-letter-routing-key", "lisi");
        // 设置过期时间
        // 1. 消息被拒， 2. 过期了 3. 队列达到最大长度
        // arguments.put("x-dead-letter-ttl",10000);

        // arguments.put("x-max-length", 6);


        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);


        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "zhangsan");
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "lisi");
        System.out.println("等待接受消息......");

        // 开启手动应答
        channel.basicConsume(NORMAL_QUEUE, false, (consumerTag, message) -> {
            String m = new String(message.getBody());
            if (m.equals("info5")) {
                System.out.println("拒绝消息 -> " + m);
                // 不放回队列
                channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
            } else {
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }
            System.out.println("Consumer01 消息为 -> " + m);
        }, (consumerTag, sig) -> {
        });
    }
}
